package com.jch.lx;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class wordcount {

    public static void main(String[] args) throws Exception {

        //创建环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //创建文件路径
        String inputPath="D:\\ideawenjian\\1019\\data\\data.txt";
        //读取文件
        DataSource<String> lines = env.readTextFile(inputPath);
        //求wc
        AggregateOperator<Tuple2<String, Integer>> sum = lines.flatMap(new FlatMapFun())
                .groupBy(0)
                .sum(1);
        sum.print();

    }
    //自定义类FlatMapFunction
    public static class FlatMapFun implements FlatMapFunction<String, Tuple2<String,Integer>> {

        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] words=s.split("\t");
            for(String word:words){
                collector.collect(new Tuple2(word,1));
            }
        }
    }


}
